<!-- 新增/修改弹框 -->
<template>
  <!-- 新增/修改弹窗 -->
  <el-dialog
    v-model="dialogAddOrEdit.visible"
    :width="screenWidth"
    :fullscreen="mobile === 'mobile'"
    :title="dialogAddOrEdit.title"
    draggable
    close-icon="CloseBold"
    :close-delay="200"
    style="margin-top: 5vh"
    @close="closeDialog(false)"
  >
    <el-form
      ref="addOrEditFormRef"
      v-loading="loading"
      :model="formData"
      :rules="rules"
      label-width="170"
      size=""
      style="padding-right: 10px; overflow: auto"
    >
      <el-row justify="start" style="margin-top: 10px">
        <el-col :span="itemSpan">
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="formData.projectName" readonly placeholder="请输入项目名称" />
            <el-button type="primary" plain style="position: absolute; right: -60px" @click="handleSelectProject"
              >选择</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="项目编号" prop="projectNum">
            <el-input v-model="formData.projectNum" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="参建单位" prop="corpId">
            <el-select v-model="formData.corpId" placeholder="请选择" clearable @change="handleSelectCorp">
              <el-option v-for="item in corpList" :key="item.corpId" :value="item.corpId" :label="item.name" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="企业社会信用代码" prop="corpName">
            <el-input v-model="formData.corpCode" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="发放工资总额" prop="totalValuation">
            <money-input v-model="formData.maxPayAmount" unit="元"></money-input>
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="发放工资人数" prop="totalValuation">
            <el-input v-model="formData.maxPersonCount" type="number" placeholder="请输入发放工资人数" />
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="选择代发月份" prop="month">
            <el-date-picker
              v-model="formData.month"
              type="month"
              format="YYYYMM"
              value-format="YYYYMM"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan"> </el-col>
      </el-row>
      <select-project :dialog-select="dialogSelectProject" @select-send-close="projectSendClose"></select-project>
    </el-form>
    <template #footer>
      <div class="dialog_footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit">{{ dialogAddOrEdit.footBtn }}</el-button>
        <el-button @click="closeDialog(false)">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import MoneyInput from "@/components/MoneyInput/index.vue";
import { CreateProjectCorpWageAuth, UpdateProjectCorpWageAuth, GetProjectCorpWageAuthForm } from "@/api/wage/index";
import { GetCorpsManager } from "@/api/common/other/index";
import { ProjectCorpWageAuthEditForm } from "@/api/wage/types";
import { useScreen } from "@/store/modules/screen";
import { FormRules } from "element-plus/es/components/form/src/types";
import SelectProject from "@/views/common/SelectProject/index.vue";

//声明变量
const screenStore = useScreen();
const mobile = computed(() => screenStore.device);
const screenWidth = ref(900);
const itemSpan = ref(12);
const props = defineProps({
  dialogAddOrEdit: {
    type: Object,
    default: () => ({
      visible: false,
      title: "新增",
      footBtn: "确认新增",
      id: undefined,
    }),
  },
});

const corpList = ref<any[]>([]);

const { dialogAddOrEdit } = toRefs(props);

const emit = defineEmits(["sendClose"]);
const loading = ref(false);

const formData = reactive<ProjectCorpWageAuthEditForm>({});
const addOrEditFormRef = ref(ElForm);

const dialogSelectProject = reactive({
  visible: false,
  title: "选择项目",
  footBtn: "确认",
  id: 0,
  type: "allproject",
});
const handleSelectProject = function () {
  dialogSelectProject.visible = true;
};
const projectSendClose = function (info: any) {
  dialogSelectProject.visible = false;
  if (info) {
    formData.projectId = info.projectId;
    formData.projectName = info.name;
    formData.projectNum = info.prjNum;
    initCorpList(info.projectId);
  }
};
const handleSelectCorp = (val: number) => {
  console.log(val);
  let temp = corpList.value.find((i) => i.corpId == val);
  if (temp) {
    formData.corpCode = temp.code;
    formData.corpName = temp.name;
    formData.corpId = temp.corpId;
  }
};

//表单验证规则
const rules = reactive<FormRules<ProjectCorpWageAuthEditForm>>({
  projectName: [{ required: true, message: "请选择项目", trigger: "blur" }],
  month: [{ required: true, message: "请选择代发月份", trigger: "blur" }],
  maxPayAmount: [{ required: true, message: "请输入发放工资总额", trigger: "blur" }],
  maxPersonCount: [{ required: true, message: "请输入发放工资人数", trigger: "blur" }],
  corpId: [{ required: true, message: "请选择参建单位", trigger: "blur" }],
});

const initCorpList = (projectId: number) => {
  GetCorpsManager({ projectId: projectId, pageSize: 9999 }).then((res) => {
    if (res.type === 0) {
      if (res.success) {
        corpList.value = res.data.list;
      } else {
      }
    } else {
    }
  });
};

function initScreen() {
  if (mobile.value === "mobile") {
    screenWidth.value = screenStore.screenWidth;
    itemSpan.value = 24;
  } else {
    screenWidth.value = 900;
    itemSpan.value = 12;
  }
}

const initForm = async function () {
  if (dialogAddOrEdit.value.id) {
    loading.value = true;
    let res = await GetProjectCorpWageAuthForm(dialogAddOrEdit.value.id);
    loading.value = false;
    if (res.type === 0) {
      if (res.success) {
        Object.assign(formData, res.data);
      } else {
      }
    } else {
    }
  }
};

onMounted(async () => {
  initScreen();
  initForm();
});

/**
 * 关闭弹窗
 */
function closeDialog(needRefresh: boolean) {
  emit("sendClose", needRefresh);
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  addOrEditFormRef.value.resetFields();
  addOrEditFormRef.value.clearValidate();
  formData.id = undefined;
}

/**
 * 项目表单提交
 */
function handleSubmit() {
  addOrEditFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;

      if (dialogAddOrEdit.value.id || dialogAddOrEdit.value.id > 0) {
        UpdateProjectCorpWageAuth(dialogAddOrEdit.value.id, formData)
          .then((res) => {
            if (res.type === 0) {
              if (res.success === true) {
                ElMessage.success(res.msg);
                closeDialog(true);
              } else {
                ElMessage.warning(res.msg);
              }
            } else {
              ElMessage.warning(res.msg);
            }
          })
          .catch((e) => {
            console.log(e);
          })
          .finally(() => (loading.value = false));
      } else {
        CreateProjectCorpWageAuth(formData)
          .then((resp) => {
            if (resp.type === 0) {
              if (resp.success === true) {
                ElMessage.success(resp.msg);
                closeDialog(true);
              } else {
                ElMessage.warning(resp.msg);
              }
            } else {
              ElMessage.warning(resp.msg);
            }
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}
</script>

<style lang="scss" scoped>
:deep(.el-form-item) {
  flex-wrap: wrap;
}

:deep(.el-input) {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}
:deep(.el-cascader) {
  width: 100%;
}
:deep(.el-input__wrapper) {
  width: 100%;
}

:deep(.el-form-item__label) {
  color: #696868;
  font-size: 13px;
}
:deep(.el-upload__tip) {
  display: inline-block;
  margin-left: 10px;
}
</style>
